/* ----------------------------------------------------------------------
*
* Copyright (C) 2025 XiaoFei. All rights reserved.
*
* @file:		XiaoFei_ADC1.c
* @author:		XiaoFei
* @Date:     	26-January-2025
* @Revision: 	V1
* @Project: 	XiaoFei BSP Library
*
* -------------------------------------------------------------------- */

#include "stm32f10x.h"
#include "XiaoFei_ADC1.h"

/* 
* @function: 	ADC1_Init
* @parameter:	[out] ADC1_Pin				 The PA(ADC1_Pin) will use ADC1 to get value.
*/
void ADC1_Init(unsigned int ADC1_Pin)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1,ENABLE);	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);	
	RCC_ADCCLKConfig(RCC_PCLK2_Div6);
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AIN;
	GPIO_InitStructure.GPIO_Pin=0x0001<<ADC1_Pin;
	GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStructure);
	#ifndef BSP_USE_ADC1
		#define BSP_USE_ADC1
		ADC_InitTypeDef ADC_InitStructure;	
		ADC_InitStructure.ADC_Mode=ADC_Mode_Independent;	
		ADC_InitStructure.ADC_DataAlign=ADC_DataAlign_Right;
		ADC_InitStructure.ADC_ExternalTrigConv=ADC_ExternalTrigConv_None;
		ADC_InitStructure.ADC_ContinuousConvMode=DISABLE;	
		ADC_InitStructure.ADC_ScanConvMode=DISABLE;
		ADC_InitStructure.ADC_NbrOfChannel=1;	
		ADC_Init(ADC1,&ADC_InitStructure);	
		ADC_Cmd(ADC1,ENABLE);
		ADC_ResetCalibration(ADC1);	
		while (ADC_GetResetCalibrationStatus(ADC1)==SET);
		ADC_StartCalibration(ADC1);
		while (ADC_GetCalibrationStatus(ADC1)==SET);
	#endif
}

/* 
* @function: 	ADC1_GetValue
* @parameter:	[out] ADC_Channel			 The PA(ADC_Channel) will use ADC1 to get value.
* @return:		The ADC1 value from PA(ADC_Channel). This value will be mapped from 0 to 3.3 volts to 0 to 4096.
*/
unsigned int ADC1_GetValue(unsigned char ADC_Channel)
{
	ADC_RegularChannelConfig(ADC1,ADC_Channel,1,ADC_SampleTime_55Cycles5);
	ADC_SoftwareStartConvCmd(ADC1,ENABLE);
	while (ADC_GetFlagStatus(ADC1,ADC_FLAG_EOC)==RESET);
	return (unsigned int)ADC1->DR;
}

/* 
* @function: 	ADC1_GetVoltage
* @parameter:	[out] ADC_Channel			 The PA(ADC_Channel) will use ADC1 to get value.
* @return:		The Voltage value from PA(ADC_Channel). This value need to be limited to 0 to 3.3 volts..
*/
float ADC1_GetVoltage(unsigned char ADC_Channel)
{
	ADC_RegularChannelConfig(ADC1,ADC_Channel,1,ADC_SampleTime_55Cycles5);
	ADC_SoftwareStartConvCmd(ADC1,ENABLE);
	while (ADC_GetFlagStatus(ADC1,ADC_FLAG_EOC)==RESET);
	return (3.3*ADC1->DR)/4096.0;
}
